import {ChooseImageResult, FileSystem} from "./index";
import Taro from "@tarojs/taro"
import ImageFile = Taro.chooseImage.ImageFile;

export class WeappFileSystem implements FileSystem {

  toBase64(file: ImageFile): Promise<string> {
    let successCallback;
    let errorCallback;
    const result = new Promise<string>((resolve, reject) => {
      successCallback = resolve
      errorCallback = reject
    });
    Taro.getFileSystemManager().readFile({
      filePath: file.path,
      encoding: "base64",
      success: res => {
        successCallback(res.data)
      },
      fail: result =>{
        errorCallback(result)
      }
    })
    return result
  }

  async toChooseImage(option: Taro.chooseImage.Option) {
    let result = await Taro.chooseImage(option);
    const resultBase64: ChooseImageResult[] = [];
    for (let tempFile of result.tempFiles) {

      let base64 = await this.toBase64(tempFile);
      resultBase64.push({imageFile: tempFile, base64})
    }
    return resultBase64
  }

  chooseImage(option: Taro.chooseImage.Option): Promise<ChooseImageResult[]> {
    return this.toChooseImage(option)
  }
}
